package com.controller;

import com.dao.AssignmentDao;
import com.model.Assignment;
import com.model.Teacher;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import javax.servlet.http.HttpSession;

@WebServlet("/teacher/assignment/*")
public class TeacherAssignmentServlet extends HttpServlet {
    private AssignmentDao assignmentDao = new AssignmentDao();
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        String pathInfo = req.getPathInfo();
        
        try {
            if (pathInfo == null || "/".equals(pathInfo) || "/list".equals(pathInfo)) {
                List<Assignment> assignments = assignmentDao.getAllAssignments();
                req.setAttribute("assignments", assignments);
                req.getRequestDispatcher("/WEB-INF/views/teacher/assignment.jsp").forward(req, resp);
            } else if ("/submissions".equals(pathInfo)) {
                int aid = Integer.parseInt(req.getParameter("aid"));
                List<Map<String, Object>> submissions = assignmentDao.getAssignmentSubmissions(aid);
                req.setAttribute("submissions", submissions);
                req.getRequestDispatcher("/WEB-INF/views/teacher/submissions.jsp").forward(req, resp);
            } else if ("/stats".equals(pathInfo)) {
                int aid = Integer.parseInt(req.getParameter("aid"));
                Map<String, Object> stats = assignmentDao.getAssignmentStats(aid);
                req.setAttribute("stats", stats);
                
                int[] gradeDistribution = assignmentDao.getGradeDistribution(aid);
                req.setAttribute("gradeDistribution", Arrays.toString(gradeDistribution));
                
                req.getRequestDispatcher("/WEB-INF/views/teacher/stats.jsp").forward(req, resp);
            } else if ("/edit".equals(pathInfo)) {
                int aid = Integer.parseInt(req.getParameter("aid"));
                Assignment assignment = assignmentDao.getAssignment(aid);
                if (assignment != null) {
                    req.setAttribute("assignment", assignment);
                    req.getRequestDispatcher("/WEB-INF/views/teacher/edit.jsp").forward(req, resp);
                } else {
                    resp.sendRedirect(req.getContextPath() + "/teacher/assignment/list");
                }
            }
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String pathInfo = req.getPathInfo();
        
        try {
            if ("/publish".equals(pathInfo)) {
                publishAssignment(req, resp);
            } else if ("/delete".equals(pathInfo)) {
                deleteAssignment(req, resp);
            } else if ("/grade".equals(pathInfo)) {
                gradeSubmission(req, resp);
            } else if ("/update".equals(pathInfo)) {
                updateAssignment(req, resp);
            }
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }
    
    private void publishAssignment(HttpServletRequest req, HttpServletResponse resp) 
            throws SQLException, IOException, ServletException {
        HttpSession session = req.getSession();
        Object userObj = session.getAttribute("user");
        if (!(userObj instanceof Teacher)) {
            System.out.println("Session中的user对象类型: " + 
                (userObj != null ? userObj.getClass().getName() : "null"));
            throw new ServletException("Teacher not logged in");
        }
        
        Teacher teacher = (Teacher) userObj;
        System.out.println("发布作业的教师信息: " + teacher.getTno() + ", " + teacher.getName());
        
        Assignment assignment = new Assignment();
        assignment.setTitle(req.getParameter("title"));
        assignment.setContent(req.getParameter("content"));
        assignment.setPublishTime(new Date());
        assignment.setTno(teacher.getTno());
        
        String deadlineStr = req.getParameter("deadline");
        if (deadlineStr != null && !deadlineStr.trim().isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                assignment.setDeadline(sdf.parse(deadlineStr));
            } catch (ParseException e) {
                throw new ServletException("Invalid date format", e);
            }
        }
        
        assignment.setStatus("进行中");
        assignmentDao.addAssignment(assignment);
        
        resp.sendRedirect(req.getContextPath() + "/teacher/assignment/list");
    }
    
    private void deleteAssignment(HttpServletRequest req, HttpServletResponse resp) 
            throws SQLException, IOException {
        int aid = Integer.parseInt(req.getParameter("aid"));
        assignmentDao.deleteAssignment(aid);
        resp.sendRedirect(req.getContextPath() + "/teacher/assignment/list");
    }
    
    private void gradeSubmission(HttpServletRequest req, HttpServletResponse resp) 
            throws SQLException, IOException {
        int submissionId = Integer.parseInt(req.getParameter("submissionId"));
        int grade = Integer.parseInt(req.getParameter("grade"));
        String comment = req.getParameter("comment");
        int aid = Integer.parseInt(req.getParameter("aid"));
        
        assignmentDao.gradeSubmission(submissionId, grade, comment);
        resp.sendRedirect(req.getContextPath() + "/teacher/assignment/submissions?aid=" + aid);
    }
    
    private void updateAssignment(HttpServletRequest req, HttpServletResponse resp) 
            throws SQLException, IOException, ServletException {
        HttpSession session = req.getSession();
        Object userObj = session.getAttribute("user");
        if (!(userObj instanceof Teacher)) {
            throw new ServletException("Teacher not logged in");
        }
        
        Teacher teacher = (Teacher) userObj;
        
        Assignment assignment = new Assignment();
        assignment.setAid(Integer.parseInt(req.getParameter("aid")));
        assignment.setTitle(req.getParameter("title"));
        assignment.setContent(req.getParameter("content"));
        assignment.setTno(teacher.getTno());
        
        String deadlineStr = req.getParameter("deadline");
        if (deadlineStr != null && !deadlineStr.trim().isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                assignment.setDeadline(sdf.parse(deadlineStr));
            } catch (ParseException e) {
                System.out.println("日期解析错误 - 输入值: " + deadlineStr);
                e.printStackTrace();
                throw new ServletException("日期格式错误，请使用 yyyy-MM-dd HH:mm:ss 格式", e);
            }
        }
        
        assignmentDao.updateAssignment(assignment);
        resp.sendRedirect(req.getContextPath() + "/teacher/assignment/list");
    }
} 